#!/bin/bash

TMP_CORRELATION_FILE=/tmp/vertices_correlation$RANDOM

OUTPUT=file.jff
INPUT=graph

echo "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!--Created with JFLAP 6.4.--><structure>" > $OUTPUT
echo "	<type>fa</type>" >> $OUTPUT
echo "	<automaton>" >> $OUTPUT
echo "		<!--The list of states.-->" >> $OUTPUT

CURRENT_JFLAP_VERTEX=0
Y_COORD=0
X_COORD=0

Y_DOWN=120
X_RIGHT=140
let Y_DOWN_LIMIT=${Y_DOWN}*4

rm $TMP_CORRELATION_FILE

function get_vertex {

	VERT=`cat $TMP_CORRELATION_FILE | egrep "^$1" | cut -d " " -f 2`

	echo $VERT
}

while read line
do

	if [[ $line =~ "Vertex:"("~")?"V"[0-9]+" ("[0-9]+")" ]] || [[ $line == "Vertex:k (2147483647)" ]]
	then

		DEC_LEVEL=`echo $line | cut -d "(" -f 2 | cut -d ")" -f 1`
		SIGN=`echo $line | cut -d ":" -f 2 | cut -d "V" -f 1`

		if [[ $line == "Vertex:k (2147483647)" ]]
		then
			CURRENT_VERTEX="k"
			SIGN=
			DEC_LEVEL=
		else
			CURRENT_VERTEX=`echo $line | cut -d " " -f 1 | cut -d "V" -f 3`
		fi

		echo "<state id=\""$CURRENT_JFLAP_VERTEX"\" name=\""${SIGN}$CURRENT_VERTEX"("$DEC_LEVEL")\">" >> $OUTPUT
		echo "	<x>${X_COORD}.0</x>" >> $OUTPUT 
		echo "	<y>${Y_COORD}.0</y>" >> $OUTPUT
		echo "</state>" >> $OUTPUT


		let Y_COORD=${Y_COORD}+${Y_DOWN}

		if [ $Y_COORD -ge $Y_DOWN_LIMIT ]
		then
			Y_COORD=0
			let X_COORD=${X_COORD}+${X_RIGHT}
		fi

		echo $CURRENT_VERTEX $CURRENT_JFLAP_VERTEX >> $TMP_CORRELATION_FILE
		let CURRENT_JFLAP_VERTEX++


	fi


done < $INPUT

echo "<!--The list of transitions.-->" >> $OUTPUT

DEST=none

while read line
do

	if [[ $line =~ "Vertex:"("~")?"V"[0-9]+" ("[0-9]+")" ]] || [[ $line == "Vertex:k (2147483647)" ]]
	then
		if [[ $line == "Vertex:k (2147483647)" ]]
		then
			DEST="k"
		else
			DEST=`echo $line | cut -d " " -f 1 | cut -d "V" -f 3`
		fi

	fi

	if [[ $line =~ "Backward:" ]]
	then
		SOURCES=`echo $line | sed -r s/' \('"(""~"?"V"[0-9]+" "")"+'\)'//g | sed s/"Backward:"//g | sed s/^" "//g`

		for source in $SOURCES
		do
			JFLAP_SOURCE=`get_vertex $source`
			JFLAP_DEST=`get_vertex $DEST`

			echo "<transition>" >> $OUTPUT
			echo "<from>${JFLAP_SOURCE}</from>" >> $OUTPUT
			echo "<to>${JFLAP_DEST}</to>" >> $OUTPUT
			# echo "<read>a</read>" >> $OUTPUT
			echo "</transition>" >> $OUTPUT

		done

	fi


done < $INPUT


echo "</automaton>" >> $OUTPUT
echo "</structure>" >> $OUTPUT

rm $TMP_CORRELATION_FILE
